<?php


namespace App\Http\Controllers\Mp;


use App\Contract\ContractStatus;
use App\Http\Controllers\Controller;
use App\Http\Resources\PaginationCollection;
use App\Http\Service\CountryService;
use App\Http\Service\DeviceService;
use App\Jobs\CheckOrder;
use App\Jobs\DeviceQuery;
use App\Model\Agent;
use App\Model\Business;
use App\Model\Contract;
use App\Model\Country;
use App\Model\Device;
use App\Model\DeviceBus;
use App\Model\DeviceBuslog;
use App\Model\DeviceLog;
use App\Model\House;
use App\Model\Repair;
use App\Model\TtlockData;
use App\Service\BaofuPay;
use App\User;
use App\Utils\Result;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;
use App\Model\BusinessConf;
use App\Model\Bill;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Str;

class DeviceController extends Controller
{
    public function indexOld(Request $request)
    {
        // Get the current page number from the request parameters (default to 1)
        $page = $request->input('page', 1);

        // Get the number of houses to show per page
        $perPage = 20;
        $keyword = $request->input('keyword');
        $houseId = $request->input('houseId');
        $status = $request->input('status');
        $warning = $request->input('is_warning');
        $query = Device::query();
        $query->where('business_id', $this->getBusinessId());
        $query->when($keyword, function ($q) use ($keyword) {
            $q->whereHas('house', function ($q) use ($keyword) {
                $q->where('estate_name', 'like', "%{$keyword}%")->orWhere('name', 'like', "%{$keyword}%");
            })->orWhere('sn', $keyword);
        });
        //->whereHas('house');
        $query->when($houseId, function ($q) use ($houseId) {
            $q->where('house_id', $houseId);
        });
        if (in_array($status, [1, 2])) {
            $query->where('status', $status);
        }
        if ($status == 3) {
            $query->where('online_status', 2);
        }
        if ($warning != '') {
            $query->where('is_warning', $warning);
        }
        // 告警设备，过载
        if ($status == 4) {
            $query->where('ems_status', 1);
        }
        // 电量不足
        if ($status == 5) {
            $query->where('low', '>', 0)->whereColumn('low', '>', 'du');
        }

        $data = $query->with('house', 'house.contract')
            ->orderBy('house_id')
            ->paginate($perPage, ['*'], 'page', $page);
        return Result::success(new PaginationCollection($data));
    }

    public function index(Request $request)
    {
        $page = $request->input('page', 1);

        // Get the number of houses to show per page
        $perPage = 20;
        $keyword = $request->input('keyword');
        $houseId = $request->input('houseId');
        $status = $request->input('status');
        $warning = $request->input('is_warning');
        $query = Device::query();
        /**
         * 改造后
         */

        $user = $this->getUser();
        if($user->type =='admin'){
            if($user->class_id){
                $class = json_decode($user->class_id,true);
            }else{
                $class = [];
            }
            $houses = House::query()->whereIn('house_class_id',$class)->pluck('id')->toArray();
            if(!$houses){
                $houses = [];
            }
            $query->leftJoin('house', 'device.house_id', '=', 'house.id');
            $query->whereIn('device.house_id', $houses);
        }else{
            $query->leftJoin('house', 'device.house_id', '=', 'house.id');
            $query->where('device.business_id', $this->getBusinessId());
        }
        $query->when($keyword, function ($q) use ($keyword) {
            $q->where(function ($q) use ($keyword) {
                // Assuming 'houses' is the correct table name for the 'house' relationship
                $q->where('house.estate_name', 'like', "%{$keyword}%")
                    ->orWhere('house.name', 'like', "%{$keyword}%")
                    ->orWhere('device.sn', $keyword);
            });
        });
        $query->when($houseId, function ($q) use ($houseId) {
            $q->where('device.house_id', $houseId);
        });
        if ($warning != '') {
            $query->where('device.is_warning', $warning);
        }

        if (in_array($status, [1, 2])) {
            $query->where('device.online_status', $status);
        }
        if ($status == 3) {
            $query->where('device.online_status', 2);
        }

        if ($status == 4) {
            $query->where('device.ems_status', 1);
        }
        if ($status == 5) {
            $query->where('device.low', '>', 0)->whereColumn('device.low', '>', 'device.du');
        }
        $query->select('device.*');
        $query->orderBy('house.estate_name', 'asc')->orderBy('house.name', 'asc');
        $data = $query
            ->with('house', 'house.fastContract') // Load the house relationship
            ->paginate($perPage, ['*'], 'page', $page);
//        foreach($country as $v){
//            if (strpos($data->house->estate_name, $v) !== false) {
//                $data->number_format($tempArr['power'], 2) = 1;
//                break;
//            }
//        }
//        foreach($data as $k => &$v){
//            if($v->qrcode == '[]'){
//                $v->qrcode = '';
//            }
//        }
        return Result::success(new PaginationCollection($data));
    }

    public function detail($id)
    {
        $device = Device::with('house', 'rate', 'business', 'business.user')->find($id);

        if (!$device) {
            return Result::success($device);
        }
        $business = Business::query()->where('id', $device->business_id)->first();
        if (!$business) {
            $device->need_people = 0;
        } else {
            $user = User::query()->where('id', $business->user_id)->first();
            $device->need_people = $user->gongan;
        }
//        if ($device->house && $user->gongan == 1) {
//            $country = Country::query()->get();
//            foreach ($country as $v) {
//                if ($v->province == $device->house->province && $v->city == $device->house->city) {
//                    if ($device->house->district) {
//                        if ($v->district == $device->house->district) {
//                            if ($device->house->country && $device->house->country == $v->country) {
//                                if ($v->name) {
//                                    if (strpos($device->house->estate_name, $v->name) !== false) {
//                                        $device->need_people = $v->type;
//                                        break;
//                                    }
//                                } else {
//                                    $device->need_people = $v->type;
//                                    break;
//                                }
//                            } else {
//                                if (strpos($device->house->estate_name, $v->name) !== false) {
//                                    $device->need_people = $v->type;
//                                    break;
//                                }
//                            }
//                        }
//                    } else {
//                        if ($device->house->country && $device->house->country == $v->country) {
//                            if ($v->name) {
//                                if (strpos($device->house->estate_name, $v->name) !== false) {
//                                    $device->need_people = $v->type;
//                                    break;
//                                }
//                            } else {
//                                $device->need_people = $v->type;
//                                break;
//                            }
//                        } else {
//                            if (strpos($device->house->estate_name, $v->name) !== false) {
//                                $device->need_people = $v->type;
//                                break;
//                            }
//                        }
//                    }
//                }
//            }
//        }
        $device->can_recharge = 1;
        if ($device->business_id) {
            $businessConf = BusinessConf::query()->where('business_id', $device->business_id)->first();
            // 账号逾期充值限制
            if ($businessConf && $businessConf->is_limit_recharge_days > 0) {
                $failBillCount = Bill::query()->where('house_id', $device->house_id)->where('is_paid', 0)
                    ->where('is_close', 0)
                    ->where('pay_date', '<', Carbon::now()->subDays($businessConf->is_limit_recharge_days)->toDateString())
                    ->count();
                if ($failBillCount > 0) {
                    $device->can_recharge = 0;
                }
            }
        }
        if ($device->qrcode == '[]') {
            $device->qrcode = '';
        }
        if($device->agent_id){
            $device->agent = Agent::query()->where('id', $device->agent_id)->first();
            if($device->agent->pid){
                $device->agent = Agent::query()->where('id', $device->agent->pid)->first();
            }
        }
        $key = 'BUSINESS_RECHARGE_CACHE'.date('Ymd').$device->id;
        if(Redis::exists($key)){
            $device->today_recharge_limit = Redis::get($key);
        }else{
            $device->today_recharge_limit = 0;
        }
        if($device->recharge_callback_at == null){
            $device->recharge_callback_at = '';
        }
        $device->bus_params = DeviceBus::query()
            ->where('device_id', $device->id)
            ->first();
        if($device->bus_params){
            if($device->bus_params->type == 1){
                $device->bus_log = DeviceBusLog::query()
                    ->where('main_device_id', $device->id)
                    ->where('created_at', '>=', date('Y-m-d'.' 00:00:00'))
                    ->where('created_at', '<=', date('Y-m-d'.' 23:59:59'))
                    ->first();
            }else{
                $device->bus_log = DeviceBusLog::query()
                    ->where('mem_device_id', $device->id)
                    ->where('created_at', '>=', date('Y-m-d'.' 00:00:00'))
                    ->where('created_at', '<=', date('Y-m-d'.' 23:59:59'))
                    ->first();
            }
        }else{
            $device->bus_log = null;
        }
        return Result::success($device);
    }

    /**手机号分享
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function shareMobile(Request $request)
    {
        $mobile = $request->input('mobile');
        if (!$mobile) {
            return Result::error(404, '请填写手机号');
        }
        $sn = $request->input('sn');
        Device::query()->where('mobile', $mobile)->update(['mobile' => '']);
        $device = Device::where('sn', $sn)->first();
        if (!$device) {
            return Result::error(404, '设备号不存在');
        }
        if (Contract::query()->where('house_id', $device->house_id)->where('status', '<=', ContractStatus::YIQIANYUE)->exists()) {
            return Result::error(402, '此房源已存在合同');
        }
        $device->mobile = $mobile;
        $device->save();
        $user = User::where('mobile', $mobile)->first();
        $house = House::query()->where('id', $device->house_id)->first();
        if (!$user) {
            $user = new User();
            $user->mobile = $mobile;
            $user->type = 'tenant';
            $user->password = Hash::make(substr((string)$mobile, 5));
            $user->save();
            $user->business()->create([
                'name' => '',
            ]);
            $user->tenant()->create([
                'name' => ''
            ]);
        }
        if ($house->country_code) {
            $business = Business::query()->where('id', $device->business_id)->first();
            $data['name'] = $user->tenant->name ? $user->tenant->name : '未实名';
            $data['phone'] = $user->mobile;
            $data['address'] = $house->province . $house->city . $house->district . $house->estate_name . $house->name;
            $data['regionCode'] = $house->country_code;
            $data['renttimeStr'] = date('Y-m-d');
            $data['landlordName'] = $business->name ? $business->name : '未实名';
            $sUser = $this->getUser();
            $data['landlordPhone'] = $sUser->mobile;
            $service = new CountryService();
            $service->pushTenant($data);
        }
        return Result::success();
    }
    # 临时设备列表
    public function tempDeviceList()
    {
        $user = $this->getUser();
        $data = $user->devices()->get();
        return Result::success($data);
    }

    public function getDeviceListByIds(Request $request)
    {
        $ids = $request->input('ids');
        $data = Device::query()->whereIn('id', $ids)->with('house')->get();
        return Result::success($data);
    }

    # 添加临时设备
    public function tempDeviceAdd(Request $request)
    {
        $id = $request->input('id');
        $sn = $request->input('sn');
        $user = $this->getUser();
        if ($id) {
            $user->devices()->attach($id);
        } elseif ($sn) {
            $device = Device::query()->where('sn', $sn)->first();
            $user->devices()->attach($device->id);
        }

        return Result::success([]);
    }


    // 设备日志
    public function log(Request $request, $id)
    {
        $page = $request->input('page', 1);
        $perPage = 20;
        $query = DeviceLog::query();
        $data = $query->orderByDesc('id')
            ->where('device_id', $id)
            ->where('action', $request->input('action', 1))
            ->paginate($perPage, ['*'], 'page', $page);
        return Result::success(new PaginationCollection($data));
    }

    public function search(Request $request)
    {
        $sn = $request->input('sn');
        $sn = trim($sn);
        $device = Device::with('house', 'rate', 'business', 'business.user')->where('sn', $sn)->first();
        if (!$device) {
            return Result::error(404, '设备不存在');
        }
        if($device->agent_id){
            $device->agent = Agent::query()->where('id', $device->agent_id)->first();
            if($device->agent->pid){
                $device->agent = Agent::query()->where('id', $device->agent->pid)->first();
            }
        }

        $device->can_recharge = 1;

        if ($device->business_id) {
            $businessConf = BusinessConf::query()->where('business_id', $device->business_id)->first();
            // 账号逾期充值限制
            if ($businessConf && $businessConf->is_limit_recharge_days > 0) {
                $failBillCount = Bill::query()->where('house_id', $device->house_id)->where('is_paid', 0)
                    ->where('is_close', 0)
                    ->where('pay_date', '<', Carbon::now()->subDays($businessConf->is_limit_recharge_days)->toDateString())
                    ->count();
                if ($failBillCount > 0) {
                    $device->can_recharge = 0;
                }
            }
        }
        $key = 'BUSINESS_RECHARGE_CACHE'.date('Ymd').$device->id;
        if(Redis::exists($key)){
            $device->today_recharge_limit = Redis::get($key);
        }else{
            $device->today_recharge_limit = 0;
        }
        return Result::success($device);
    }

    public function create(Request $request)
    {
        $user = $this->getUser();
        if ($user->is_disabled == 1) {
            return Result::error(401, '账户异常 请联系客服400-926-2566');
        }

        $deviceModel = Device::query()->where('sn', $request->input('sn'))->with('house')->first();
        if ($deviceModel && $deviceModel->house_id) {
            return Result::error(401, '设备已被绑定，无法重复绑定');
        }
        if (!$deviceModel) {
            return Result::error(401, '设备不存在');
            /*$deviceModel = new Device();
            $deviceModel->fill($request->all());
            $deviceModel->bind_at = Carbon::now()->toDateTimeString();
            $deviceModel->expired_at = Carbon::now()->addYears(8)->toDateTimeString();*/
        }
        if ($request->input('price') > 3 && $deviceModel->type != 2) {
            return Result::error(401, '电量单价不可超过3元');
        }
        if ($request->input('price') > 10 && $deviceModel->type == 2) {
            return Result::error(401, '电量单价不可超过3元');
        }

        $business = Business::query()->where('user_id', $user->id)->first();
        if ($business->agent_id) {
            if ($business->agent_id != $deviceModel->agent_id && $deviceModel->type != 2) {
                $agent = Agent::query()->where('id', $business->agent_id)
                    ->first();
                $str = '绑定异常，请联系您的专属客服';
                if ($agent) {
                    if ($agent->tel_no) {
                        $str .= ":({$agent->tel_no})";
                    } else {
                        $str .= ":({$agent->mobile})";
                    }
                }
                return Result::error(401, $str);
            }
        } else {
            $business->agent_id = $deviceModel->agent_id;
            $business->save();
        }
        $deviceModel->house_id = $request->input('house_id');
        if ($request->input('price') > 3 && $deviceModel->type != 2) {
            return Result::error(401, '电量单价不可超过3元');
        }

        if ($request->input('price') > 10 && $deviceModel->type == 2) {
            return Result::error(401, '水费单价不可超过10元/吨');
        }
        if ($request->input('basic_price') !== false) {
            $deviceModel->basic_price = $request->input('basic_price');
        }
        if ($request->input('service_price') !== false) {
            $deviceModel->service_price = $request->input('service_price');
        }
        $deviceModel->price = $request->input('price');
        $deviceModel->alias = $request->input('alias');
        $deviceModel->business_id = $this->getBusinessId();
        $deviceModel->bind_at = Carbon::now()->toDateTimeString();
        $deviceModel->business_amount = $user->month_amount;
        if (!$deviceModel->expired_at) {
            $deviceModel->expired_at = Carbon::now()->addYears(10)->toDateTimeString();
        }

        $deviceModel->save();
        if ($request->input('house_id')) {
            $deviceModel->house_id = $request->input('house_id');
            $new = House::query()->where('id', $deviceModel->house_id)->first();
            $str = $deviceModel->sn . '房源调整:' . $new->country . $new->name;
            $save['action'] = 11;
            $save['device_id'] = $deviceModel->id;
            $save['log'] = $str;
            $save['user_name'] = $this->getUser()->mobile;
            DeviceLog::create($save);
        }
        return Result::success($deviceModel);
    }

    public function getBusinessConf(Request $request){
        $sn = $request->input('sn');
        $businessId = Device::query()->where('sn',$sn)->value('business_id');
        if (!$businessId) {
            return Result::error(1001,'房东信息不存在');
        }
        $businessConf = BusinessConf::query()->where('business_id',$businessId)
            ->first(['show_basic_price','show_service_price']);
        return Result::success($businessConf);
    }

    public function update(Request $request, $id)
    {
        $deviceModel = Device::where('id', $id)->first();
        //$deviceModel->fill($request->all());

        if ($request->input('house_id')) {
            $oldHouseId = $deviceModel->house_id;
            $deviceModel->house_id = $request->input('house_id');
            if ($oldHouseId) {
                $old = House::query()->where('id', $oldHouseId)->first();
                $new = House::query()->where('id', $deviceModel->house_id)->first();
                $str = $deviceModel->sn . '房源调整:' . $old->country . $old->name . '改为' . $new->country . $new->name;
            } else {
                $new = House::query()->where('id', $deviceModel->house_id)->first();
                $str = $deviceModel->sn . '房源调整:' . $new->country . $new->name;
            }
            $save['action'] = 11;
            $save['device_id'] = $deviceModel->id;
            $save['log'] = $str;
            $save['user_name'] = $this->getUser()->mobile;
            DeviceLog::create($save);
        }
        if ($request->input('low') != false) {
            $deviceModel->low = $request->input('low');
        }
        if ($request->input('price') != false) {
            if ($request->input('price') > 3 && $deviceModel->type != 2) {
                return Result::error(401, '电量单价不可超过3元');
            }

            if ($request->input('price') > 10 && $deviceModel->type == 2) {
                return Result::error(401, '水费单价不可超过10元/吨');
            }
            if ($request->input('price') < 0.1) {
                return Result::error(401, '电量单价不可小于0.1元');
            }
            $deviceModel->price = $request->input('price');
        }
        if($request->input('basic_price') != false){
            $deviceModel->basic_price = $request->input('basic_price');
        }
        if($request->input('service_price') != false){
            $deviceModel->service_price = $request->input('service_price');
        }
        $deviceModel->save();
        $deviceModel->load('house');
        return Result::success($deviceModel);
    }

    public function unbind($id)
    {
        $deviceModel = Device::query()->where('business_id', $this->getBusinessId())->find($id);
        if (!$deviceModel) {
            return Result::error(404, '设备不存在');
        }
        $new = House::query()->where('id', $deviceModel->house_id)->first();
        $str = $deviceModel->sn . '房源解绑:' . $new->country . $new->name;
        $save['action'] = 11;
        $save['device_id'] = $deviceModel->id;
        $save['log'] = $str;
        $save['user_name'] = $this->getUser()->mobile;
        DeviceLog::create($save);

        $deviceModel->house_id = 0;
        $deviceModel->bind_at = null;
        $deviceModel->save();

        return Result::success();
    }

    /**修改公摊
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function speedLog(Request $request)
    {
        $user = $this->getUser();
        $deviceId = $request->input('device_id', 0);
        $deviceModel = Device::query()->where('id', $deviceId)->first();
        $speed = $request->input('speed');
        try {
            DeviceLog::create(
                [
                    'action' => 6,
                    'device_id' => 'device_id',
                    'log' => '读取的公摊损耗:' . $deviceModel->speed . '，修改的损耗:' . $speed,
                    'user_id' => $user->id
                ]
            );
            return Result::success();
        } catch (\Exception $e) {
            return Result::error('1001', '操作繁忙');
        }
    }
    public function read(Request $request, $id)
    {
        $deviceModel = Device::where('id', $id)->first();
        $before = $deviceModel->du;
        $info = $request->input('info');
        $data = $request->all();
        if(isset($data['info'])){
            unset($data['info']);
        }
        $log = 0;
        if(isset($data['log'])){
            $log = $data['log'];
            unset($data['log']);
        }
        $deviceModel->fill($data);
        $deviceModel->read_at = now()->toDateTimeString();
        $deviceModel->save();
        $service = app()->make(DeviceService::class);
        if($deviceModel->du == 0 && $deviceModel->online_status != 1 && $info == 'business'){
            DeviceLog::create([
                'action' => 1,
                'device_id' => $deviceModel->id,
                'log' => '电量手动清零或抄表后剩余电量为0'.'，总电量:' . $deviceModel->total,
                'user_name' => $service->getUserName(),
                'before'=>$before,
                'after'=>0
            ]);
        }else{
            try {
                if($log){
                    DeviceLog::create(
                        [
                            'action' => 5,
                            'device_id' => $deviceModel->id,
                            'log' => '抄表后余量:' . $deviceModel->du . '，总电量:' . $deviceModel->total,
                            'user_name' => $service->getUserName(),
                            'before' => $before,
                            'after' => $deviceModel->du
                        ]
                    );
                }
            } catch (\Exception $e) {
                Log::info($e->getMessage());
            }
        }
        return Result::success($deviceModel);
    }

    public function destroy($id)
    {
        $deviceModel = Device::where('id', $id)->where('business_id', $this->getBusinessId())->first();
        if ($deviceModel) {
            if ($deviceModel->house_id) {
                $devices = Device::where('house_id', $deviceModel->house_id)
                    ->where('id', '<>', $id)
                    ->count();
                $locks = TtlockData::query()->where('house_id', $deviceModel->house_id)->count();
                if ($devices <= 0 && $locks <= 0) {
                    House::query()->where('id', $deviceModel->house_id)->delete();
                }
            }
            //$deviceModel->delete();
            $deviceModel->business_id = 0;
            $deviceModel->house_id = 0;
            $deviceModel->save();
            $checkBus = DeviceBus::query()->where('device_id', $deviceModel->id)->first();
            if($checkBus){
                DeviceBus::query()->where('pid',$checkBus->id)->delete();
                $checkBus->delete();
            }
        }
        return Result::success();
    }

    # 拉闸
    public function stop(Request $request)
    {
        $deviceModel = Device::where('mac', $request->input('mac'))->where('business_id', $this->getBusinessId())->first();
        if (!$deviceModel) {
            return Result::error(404, '设备不存在');
        }
        $service = app()->make(DeviceService::class);
        $result = $service->stop($request->input('mac'));

        return Result::success();
    }

    public function setMode(Request $request)
    {
        $type = $request->input('type');
        $service = app()->make(DeviceService::class);
        $service->setMode($request->input('mac'), $type);
        sleep(6);
        $device = Device::query()->where('mac', $request->input('mac'))->first(['sn', 'pay_type', 'online_status', 'signal']);
//        if($device->pay_type == $type){
//            $service->restart($request->input('mac'));
//        }
        return Result::success($device);
    }

    /**创建公摊
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function setBus(Request $request)
    {
        $deviceId = $request->input('device_id');
        $count_type = $request->input('count_type',1);
        $device = Device::query()->where('id', $deviceId)->first();
        if (!$device) {
            return Result::error(404, '设备不存在');
        }
        if($device->bus_type != 2){
            return Result::error(404, '设备不支持设为公摊');
        }
        $check = DeviceBus::query()->where('device_id', $deviceId)
            ->where('type', 1)->first();
        if ($check) {
            return Result::error(404, '该表已生成公摊，无需重复添加');
        }
        $house = House::query()->where('id', $device->house_id)->first();
        if (!$house || !$house->house_class_id) {
            return Result::error(404, '设备未绑定或房源未设置分组');
        }
        $save['device_id'] = $deviceId;
        $save['name'] = $device->sn . '-' . '公摊';
        $save['business_id'] = $this->getBusinessId();
        $save['sn'] = $device->sn;
        $save['count_type'] = $count_type;
        $save['device_total'] = $device->total;
        $save['class_id'] = $house->house_class_id;
        $deviceBus = DeviceBus::create($save);
        return Result::success($deviceBus);
    }

    public function editBus(Request $request){
        $busId = $request->input('bus_id');
        if (!$busId) {
            return Result::error(404, '缺少参数公摊数据id');
        }
        $count_type = $request->input('count_type',1);
        DeviceBus::query()->where('id', $busId)->update(['count_type'=>$count_type]);
        return Result::success();
    }

    public function editBusAuto(Request $request){
        $auto = $request->input('is_autoload',1);
        $busId = $request->input('bus_id');
        DeviceBus::query()->where('id', $busId)->update(['is_autoload'=>$auto]);
        if($auto){
            $count = DeviceBus::query()->where('type', 2)
                ->where('status',1)
                ->where('pid', $busId)->count();
            if($count  > 0){
                $rate = number_format(100 / $count, 2);
                DeviceBus::query()->where('type', 2)
                    ->where('status',1)
                    ->where('pid', $busId)
                    ->update(['rate' => $rate]);
            }
        }
        return Result::success();
    }

    /**移除子表或公摊表
     * @param Request $request
     * @return void
     */
    public function removeBus(Request $request)
    {
        $busId = $request->input('bus_id');
        if (!$busId) {
            return Result::error(404, '缺少参数公摊数据id');
        }
        $check = DeviceBus::query()->where('id', $busId)->first();
        if(!$check){
            return Result::error(404, '公摊信息不存在');
        }
        $type = $check->type;
        if($type == 1){
            DeviceBus::query()->where('id', $busId)->delete();
            DeviceBus::query()->where('pid', $busId)->delete();
        }else{
            $pid = $check->pid;
            DeviceBus::query()->where('id', $busId)->delete();
            $count = DeviceBus::query()->where('type', 2)
                ->where('status',1)
                ->where('pid', $pid)->count();
            if($count== 0){
                return Result::success();
            }
            $rate = number_format(100 / $count, 2);
            DeviceBus::query()->where('type', 2)
                ->where('status',1)
                ->where('pid', $busId)
                ->update(['rate' => $rate]);
        }
        return Result::success();
    }

    public function normalRate(Request $request)
    {
        $busId = $request->input('bus_id');
        if (!$busId) {
            return Result::error(404, '缺少参数公摊数据id');
        }
        $count = DeviceBus::query()->where('type', 2)
            ->where('status',1)
            ->where('pid', $busId)->count();
        if($count== 0){
            return Result::success();
        }
        $rate = number_format(100 / $count, 2);
        DeviceBus::query()->where('type', 2)
            ->where('status',1)
            ->where('pid', $busId)
            ->update(['rate' => $rate]);
        return Result::success();
    }


    public function busLog(Request $request)
    {
        $page = $request->input('page', 1);
        $limit = $request->input('limit', 10);
        $status = $request->input('status', 1);
        $log_id = $request->input('log_id');
        $class_id = $request->input('class_id');
        $date = $request->input('date');
        $query = DeviceBuslog::query();
        if($status != ''){
            $query->where('status', $status);
        }
        if ($class_id) {
            $query->where('class_id', $class_id);
        }
        if ($date) {
            $carbonDate = Carbon::parse($date . '-01'); // 加上'-01'确保它是这个月的第一天
            $firstDayOfMonth = $carbonDate->copy()->startOfMonth()->toDateString();
            $lastDayOfMonth = $carbonDate->copy()->endOfMonth()->toDateString();
            $query->where('created_at', '>=', $firstDayOfMonth . ' 00:00:00');
            $query->where('created_at', '<=', $lastDayOfMonth . ' 23:59:59');
        }
        if ($log_id) {
            $query->where('log_id', $log_id);
            $query->where('type', 2);
            $query->with('device', 'device.house');
        } else {
            $query->where('type', 1);
            $query->where('business_id', $this->getBusinessId());
        }
        $data['total'] = $query->count();
        $query->offset(($page - 1) * $limit);
        $query->limit($limit);
        $data['list'] = $query->orderBy('id','desc')->get();
        return Result::success($data);
    }

    /**加入公摊
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function joinBus(Request $request)
    {
        $deviceId = $request->input('device_id');
        $device = Device::query()->where('id', $deviceId)->first();
        $pid = $request->input('pid');
        if (!$device) {
            return Result::error(404, '设备不存在');
        }
        $pInfo = DeviceBus::query()->where('id', $pid)->first();
        $model = DeviceBus::query()->where('device_id', $deviceId)
            ->where('pid', $pid)->first();
        if (!$model) {
            $type = 'add';
            $model = new DeviceBus();
        } else {
            $type = 'edit';
            $rate = $request->input('rate');
        }
        $model->pid = $pid;
        $model->device_id = $deviceId;
        $model->type = 2;
        $model->class_id = $pInfo->class_id;
        $model->count_type = $pInfo->count_type;
        $model->name = $device->sn . '-子表';
        $model->business_id = $this->getBusinessId();
        $model->sn = $device->sn;
        $model->rate = $rate??0;
        $model->device_total = $device->total;
        if ($request->input('remark') !== '') {
            $model->remark = $request->input('remark');
        }
        if ($request->input('status') !== '') {
//            if($model->status != $request->input('status')){
                $type = 'change';
//            }
            $model->status = $request->input('status');
        }
        if ($request->input('clear') !== '') {
            $model->clear = $request->input('clear');
        }
        if ($request->input('recharge') !== '') {
            $model->recharge = $request->input('recharge');
        }
        $model->save();
        if($type == 'add'){
            $count = DeviceBus::query()->where('type', 2)
                ->where('status',1)
                ->where('pid', $pid)->count();
            if($count){
                $rate = number_format(100 /$count, 2);
                DeviceBus::query()->where('type', 2)
                    ->where('pid', $pid)
                    ->where('status',1)
                    ->update(['rate' => $rate]);
            }
        }
        if($type == 'change'){
            $bus = DeviceBus::query()->where('id', $pid)->first();
            if($bus->is_autoload){
                $count = DeviceBus::query()->where('type', 2)
                    ->where('status',1)
                    ->where('pid', $pid)->count();
                if($count){
                    $rate = number_format(100 /$count, 2);
                    DeviceBus::query()->where('type', 2)
                        ->where('status',1)
                        ->where('pid', $pid)
                        ->update(['rate' => $rate]);
                }
            }
        }
        return Result::success();
    }

    /**公摊详情
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function busDetail(Request $request)
    {
        $deviceId = $request->input('device_id');
        $data = DeviceBus::query()->where('device_id', $deviceId)
            ->where('type', 1)->first();
        if (!$data) {
            return Result::error(404, '该表公摊信息不存在');
        }
        $data->all_device = DeviceBus::query()
            ->where('pid', $data->id)
            ->where('type', 2)->count();
        $data->start_device = DeviceBus::query()
            ->where('pid', $data->id)
            ->where('type', 2)
            ->where('status', 1)
            ->count();
        $data->all_rate = DeviceBus::query()
            ->where('pid', $data->id)
            ->where('type', 2)
            ->where('status', 1)
            ->sum('rate');
        return Result::success($data);
    }

    /**扣除度数
     * @param Request $request
     * @return void
     * @throws \Illuminate\Contracts\Container\BindingResolutionException
     */
    public function editDu(Request $request)
    {
        $du = $request->input('du');
        $service = app()->make(DeviceService::class);
        $service->editDu($request->input('mac'), $du);
    }

    # 合闸
    public function start(Request $request)
    {
        $deviceModel = Device::where('mac', $request->input('mac'))->where('business_id', $this->getBusinessId())->first();
        if (!$deviceModel) {
            return Result::error(404, '设备不存在');
        }
        $service = app()->make(DeviceService::class);
        $result = $service->start($request->input('mac'));

        return Result::success();
    }

    # 充值
    public function recharge(Request $request)
    {
        $isRecharged = $request->input('isRecharged') ?? 0;
        $isPaid = $request->input('isPaid') ?? 0;
        $deviceModel = Device::where('mac', trim($request->input('mac')))->first();
        if (!$deviceModel) {
            return Result::error(404, '设备不存在');
        }
        if($deviceModel->recharge_disabled == 1){
            return Result::error(404, '设备充值被限制');
        }
//        if($deviceModel->signal == 0){
//            return Result::error(1001, '当前设备暂无信号');
//        }
        if ($request->input('du') > 10000) {
            return Result::error(404, '单次充值量不可超过1万');
        }
        $deviceModel = Device::query()->where('mac', trim($request->input('mac')))->first();
        if ($deviceModel->du >= 100000) {
            return Result::error(404, '当前余量已超过10万无需充值');
        }
        $businessId = $this->getBusinessId();
        Log::info('房东id充值'.$deviceModel->business_id.'----'.$businessId);
        if($deviceModel->business_id != $businessId){
            return Result::error(404,'您当前不是该设备房东，无法进行房东充值');
        }
        $amount = $request->input('du')*$deviceModel->price;
        $monthKey = 'device_month_business_'.date('Ym').'_'.$deviceModel->id;
        $current = Redis::get($monthKey);
        if($current+$amount > $deviceModel->business_amount){
            return Result::error(404,'当前设备剩余房东充值额度为'.round($deviceModel->business_amount-$current,2).'元');
        }
        // todo 验证支付单
        $service = app()->make(DeviceService::class);
        $addBill = $request->input('addBill',1);
        $user = $this->getUser();
        if($user->type == 'admin'){
            if($request->input('du') > 1){
                Log::info('管理员充值'.json_encode($user).$request->input('du').$request->input('mac'));
                return Result::error(404,'管理员充值电量不可大于1度');
            }
        }
        if($addBill){
            $result = $service->recharge(trim($request->input('mac')), $request->input('du'), $request->input('amount'), $isRecharged, $isPaid);
        }else{
            $result = $service->rechargeNoBill(trim($request->input('mac')), $request->input('du'), $request->input('amount'), $isRecharged, $isPaid);
        }
        for($i=1;$i<4;$i++){
            dispatch(new DeviceQuery(trim($request->input('mac'))))->delay(6*$i);
        }
        $busInfo = DeviceBus::query()->where('device_id', $deviceModel->id)
            ->first();
        if ($busInfo && $busInfo->recharge) {
            $busInfo->device_total = $deviceModel->total;
            $busInfo->status = 1;
            $busInfo->save();
            $bus = DeviceBus::query()->where('id', $busInfo->pid)->first();
            if($bus && $bus->is_autoload){
                $count = DeviceBus::query()->where('type', 2)
                    ->where('status',1)
                    ->where('pid', $busInfo->pid)->count();
                $rate = number_format(100 /$count, 2);
                DeviceBus::query()->where('type', 2)
                    ->where('pid', $busInfo->pid)
                    ->where('status',1)
                    ->update(['rate' => $rate]);
            }
        }
        return Result::success();
    }

    public function clearSuccess(Request $request){
        $deviceId = $request->input('id');
        $log = $request->input('log');
        $before = $request->input('before');
        $service = app()->make(DeviceService::class);
        DeviceLog::create([
            'action' => 1,
            'device_id' =>$deviceId,
            'log' =>$log,
            'user_name' => $service->getUserName(),
            'before'=>$before,
            'after'=>0
        ]);
        return Result::success();
    }

    # 清0
    public function clear(Request $request)
    {
        $user = $this->getUser();
        $deviceModel = Device::where('mac', $request->input('mac'))->where('business_id', $this->getBusinessId())->first();
        if (!$deviceModel) {
            return Result::error(404, '设备不存在');
        }
        $service = app()->make(DeviceService::class);
        $result = $service->clear($request->input('mac'));
        $busInfo = DeviceBus::query()->where('device_id',$deviceModel->id)
            ->first();
        if($busInfo && $busInfo->clear){
            $busInfo->status = 0;
            $busInfo->save();
            $bus = DeviceBus::query()->where('id', $busInfo->pid)->first();
            if($bus && $bus->is_autoload){
                $count = DeviceBus::query()->where('type', 2)
                    ->where('status',1)
                    ->where('pid', $busInfo->pid)->count();
                $rate = number_format(100 /$count, 2);
                DeviceBus::query()->where('type', 2)
                    ->where('pid', $busInfo->pid)
                    ->where('status',1)
                    ->update(['rate' => $rate]);
            }
        }
        return Result::success();
    }

    # 调表计量系数
    public function speed(Request $request)
    {
        $deviceModel = Device::where('mac', $request->input('mac'))->where('business_id', $this->getBusinessId())->first();
        if (!$deviceModel) {
            return Result::error(404, '设备不存在');
        }

        $businessModel = Business::where('id', $this->getBusinessId())->first();
        if($request->input('speed')>$businessModel->max_speed && $deviceModel->type != 4){
            return Result::error(404, '公摊设置超限！请重新输入！');
        }
        $service = app()->make(DeviceService::class);
        $result = $service->speed($request->input('mac'), $request->input('speed', 1));

        return Result::success();
    }

    # 读表计量系数
    public function querySpeed(Request $request)
    {
        $deviceModel = Device::where('mac', $request->input('mac'))->where('business_id', $this->getBusinessId())->first();
        if (!$deviceModel) {
            return Result::error(404, '设备不存在');
        }
        $service = app()->make(DeviceService::class);
        $result = $service->querySpeed($request->input('mac'), $request->input('speed', 1));

        return Result::success();
    }

    public function statusQuery(Request $request)
    {
        Log::notice('statusQuery', $request->all());
        $deviceModel = Device::where('mac', $request->input('mac'))->where('business_id', $this->getBusinessId())->first();
        if (!$deviceModel) {
            return Result::error(404, '设备不存在');
        }
        $service = app()->make(DeviceService::class);
        $result = $service->statusQuery($request->input('mac'));

        return Result::success();
    }

    public function restart(Request $request)
    {
        $deviceModel = Device::where('mac', $request->input('mac'))->first();
        if (!$deviceModel) {
            return Result::error(404, '设备不存在');
        }
        $service = app()->make(DeviceService::class);
        $result = $service->restart($request->input('mac'));
        return Result::success();
    }

    /**amount当度数理解
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function incrBusinessAmount(Request $request){
        $device_id = $request->input('device_id');
        $amount = $request->input('amount');
        $floatAmount = floatval($amount);
        if(!$device_id){
            return Result::error(404, '设备不存在');
        }
        $device = Device::query()->where('id',$device_id)->first();
        if(!$device){
            return Result::error(404, '设备不存在');
        }
//        if($device->business_id != $this->getBusinessId()){
//            return Result::error(404, '设备不存在');
//        }
        $monthKey = 'device_month_business_'.date('Ym').'_'.$device_id;
        if(Redis::exists($monthKey)){
            $current = Redis::get($monthKey);
            if($current+$floatAmount > $device->business_amount){
                $return_du = $device->business_amount-$current;
                $return_du = $return_du>0?$return_du:0;
                return Result::error(404, '剩余可充电量为'.$return_du.'度');
            }
            Redis::incrbyFloat($monthKey,$floatAmount);
        }else{
           if($amount > $device->business_amount){
               return Result::error(404, '剩余可充电量为'.$device->business_amount.'度');
           }
            Redis::setex($monthKey,3600*24*32,$floatAmount);
        }
        $data['current'] = Redis::get($monthKey);
        $data['month'] = date('Ym');
        return Result::success($data);
    }

    public function getBusinessAmount(Request $request){
        $device_id = $request->input('device_id');
        if(!$device_id){
            return Result::error(404, '设备不存在');
        }
        $device = Device::query()->where('id',$device_id)->first();
        if(!$device){
            return Result::error(404, '设备不存在');
        }
        $monthKey = 'device_month_business_'.date('Ym').'_'.$device_id;
        $data['current'] = Redis::get($monthKey);
        $data['month'] = date('Ym');
        return Result::success($data);
    }


    public function getAdmin(Request $request){
        $sn = $request->input('sn');
        $device = Device::where('sn',$sn)->first();
        if(!$device->house_id){
            return Result::error(404, '未绑定房源');
        }
        $house = House::where('id',$device->house_id)->first();
        $business = Business::find($device->business_id);
        $users = User::query()->where('parent_id',$business->user_id)->get();
        $userInfo = [];
        foreach($users as $user){
            if($user->class_id){
                $classId = json_decode($user->class_id);
                if(in_array($house->house_class_id,$classId)){
                    $userInfo = $user;
                    break;
                }
            }
        }
        return Result::success($userInfo);
    }

    public function queryAmount(Request $request){
        $contractNo = $request->input('contractNo');
        $bfAccount  = app::make(BaofuPay::class);
        return $bfAccount->queryAmount($contractNo);
    }


    public function restartMaster(Request $request)
    {
        $deviceModel = Device::where('mac', $request->input('mac'))->first();
        if (!$deviceModel) {
            return Result::error(404, '设备不存在');
        }
        $masterDevice = Device::where('mac',$deviceModel->m_mac)->first();
        if(!$masterDevice){
            return Result::error(404, '未找到主设备');
        }
        if($masterDevice->online_status != 1){
            return Result::error(404, '主设备不在线');
        }
        $key = 'cache_restart_'.$masterDevice->mac;
        if(Redis::exists($key)){
            return Result::error(404, '设备5分钟内请勿多次重启');
        }
        $service = app()->make(DeviceService::class);
        $result = $service->restart($masterDevice->mac);
        Redis::setex($key,5*60,1);
        return Result::success();
    }

}
